/*
 * Copyright 2010, 2011 Matt Oliveri
 *
 * This file is part of JConfigGen
 *
 * JConfigGen is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * JConfigGen is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with JConfigGen.  If not, see <http://www.gnu.org/licenses/>.
 */

package atma.jconfiggen;

import java.io.PrintStream;
import java.util.List;
import java.util.Collections;

/** Object instantiation expression.
 * <p>
 * A {@code NewObj} expression is evaluated by first evaluating the arguments in order, then performing the object instantiation.
 * The result of a {@code NewObj} is the newly constructed object.
 * A {@code NewObj} expression can be optionally assigned an id.
 * </p>
 */
public final class NewObj extends TupleExpr
{
	private final String clss;
	private final String types;
	private final String argstr;

	/** Construct a {@code NewObj} with a {@code List<Expr>} for arguments.
	 * @param c The {@link Config} that will contain this expression.
	 * @param s The class to instantiate.
	 * @param t The result type of this expression, or null.
	 * @param i The id to assign to this expression, or null.
	 * @param e A list of subexpressions of the {@code NewObj} to use as constructor arguments. Can be empty, but not null.
	 */
	public NewObj(Config c,String s,String t,String i,List<Expr> e)
	{
		super(c,i,e);
		clss = s;
		types = t;
		argstr = null;
	}

	/** Construct a {@code NewObj} with a Java argument list {@link String}.
	 * @param c The {@link Config} that will contain this expression.
	 * @param s The class to instantiate.
	 * @param t The result type of this expression, or null.
	 * @param i The id to assign to this expression, or null.
	 * @param a A Java argument list, not including parentheses, to use as constructor arguments. Use an empty string for no arguments. E.g.: {@code "someID, true"}, {@code ""}
	 */
	public NewObj(Config c,String s,String t,String i,String a)
	{
		super(c,i,Collections.<Expr>emptyList());
		clss = s;
		types = t;
		argstr = a;
	}

	void printType(PrintStream out)
	{
		out.print(clss);
		if (types == null) return;
		out.print('<');
		out.print(types);
		out.print('>');
	}

	void printCore(PrintStream out)
	{
		out.print("new ");
		printType(out);
		out.print('(');
		if (argstr == null) printElems(out);
		else out.print(argstr);
		out.print(')');
	}
}
